﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MvcDeviceManager.Models;
using MvcDeviceManager.Util;
using System.Collections;

namespace MvcDeviceManager.Service
{
    
    public class MenuService
    {
     
        public IList<Menu> getMenuTree()
        {
            IList<Menu> list = DaoUtil.getSqlMapper().QueryForList<Menu>("MvcDeviceManager.Models.Menu.selectRoot", null);
            foreach(Menu m in list){
                m.Children = getMenuByParentId(m.MenuId);
            }
            return list;
        }
        private IList<Menu> getMenuByParentId(string id)
        {
            IList<Menu> list = DaoUtil.getSqlMapper().QueryForList<Menu>("MvcDeviceManager.Models.Menu.selectMenusByParentId", id);
            foreach (Menu m in list)
            {
                m.Children = getMenuByParentId(m.MenuId);
            }
            return list;
        }

        public IList<Menu> getMenuTreeByMenuIds(ISet<string> menuIds)
        {
            ISet<Menu> menus = new HashSet<Menu>();
            foreach (string menuId in menuIds)
            {
                menus.Add(getMenuByMenyId(menuId));
            }
            ISet<Menu> temp = new HashSet<Menu>();
            foreach (Menu m in menus)
            {
                if (m.ParentId != null)
                {
                    temp.Add(getMenuByMenyId(m.ParentId));
                }
            }
            foreach (Menu m in temp)
            {
                menus.Add(m);
            }
            return BuildMenuTree(menus);
        }
        private IList<Menu> getMenusByPatenrId(ISet<Menu> menus, string parentId)
        {
            List<Menu> tree = new List<Menu>();
            foreach (Menu m in menus)
            {
                if (parentId == null)
                {
                    if (m.ParentId == null)
                    {
                        tree.Add(m);
                    }
                }
                else if (parentId.Equals(m.ParentId))
                {
                    tree.Add(m);
                }
                
                
            }
            return tree.OrderBy<Menu, string>(m => m.MenuId).ToList<Menu>();
        }
        private IList<Menu> BuildMenuTree(ISet<Menu> menus)
        {
            IList<Menu> tree = getMenusByPatenrId(menus,null);
            
            foreach (Menu m in tree)
            {
                m.Children = getMenusByPatenrId(menus, m.MenuId);
            }
            return tree;
        }
        public Menu getMenuByMenyId(string menuId)
        {
            return DaoUtil.getSqlMapper().QueryForObject<Menu>("MvcDeviceManager.Models.Menu.selectMenusByMenuId", menuId);
        }
    }
}